import socket

# 创建一个TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定地址和端口
server_address = ('localhost', 12345)
server_socket.bind(server_address)

# 开始监听连接
server_socket.listen(1)
print('服务器正在监听端口 12345...')

while True:
    # 等待客户端连接
    print('等待客户端连接...')
    client_socket, client_address = server_socket.accept()
    print(f'客户端 {client_address} 已连接')

    try:
        # 接收客户端消息
        data = client_socket.recv(1024)
        if data:
            message = data.decode('utf-8')
            print(f'收到消息: {message}')

            # 发送响应给客户端
            response = '服务器已收到你的消息'.encode('utf-8')
            client_socket.sendall(response)
    finally:
        # 关闭客户端连接
        client_socket.close()